﻿using System.Collections.Generic;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;

namespace MedicService.Server.Utils {

    public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable {
        #region IXmlSerizable methods
        void IXmlSerializable.WriteXml(XmlWriter w) {
            XmlSerializer keySer = new XmlSerializer(typeof(TKey));
            XmlSerializer valueSer = new XmlSerializer(typeof(TValue));
            w.WriteStartElement("Dictionary");
            foreach (KeyValuePair<TKey, TValue> pair in this) {
                w.WriteStartElement("KeyValuePair");
                w.WriteStartElement("Key");
                keySer.Serialize(w, pair.Key);
                w.WriteEndElement();
                w.WriteStartElement("Value");
                valueSer.Serialize(w, pair.Value);
                w.WriteEndElement();
                w.WriteEndElement();
            }
            w.WriteEndElement();
        }

        void IXmlSerializable.ReadXml(XmlReader r) {
            XmlSerializer keySer = new XmlSerializer(typeof(TKey));
            XmlSerializer valueSer = new XmlSerializer(typeof(TValue));
            r.Read();
            r.ReadStartElement("Dictionary");
            while (r.NodeType != XmlNodeType.EndElement) {
                r.ReadStartElement("KeyValuePair");
                r.ReadStartElement("Key");
                TKey key = (TKey)keySer.Deserialize(r);
                r.ReadEndElement();
                r.ReadStartElement("Value");
                TValue value = (TValue)valueSer.Deserialize(r);
                r.ReadEndElement();
                this.Add(key, value);
                r.ReadEndElement();
                r.MoveToContent();
            }
            r.ReadEndElement();
            r.ReadEndElement();
        }

        XmlSchema IXmlSerializable.GetSchema() {
            return null;
        }
        #endregion
    }
}

